package com.sam.nosql;

import android.test.InstrumentationTestCase;
import android.util.Log;

import com.couchbase.lite.Attachment;
import com.couchbase.lite.CouchbaseLiteException;
import com.couchbase.lite.Database;
import com.couchbase.lite.Document;
import com.couchbase.lite.Manager;
import com.couchbase.lite.SavedRevision;
import com.couchbase.lite.UnsavedRevision;
import com.couchbase.lite.android.AndroidContext;
import com.sam.data.DbDataUtil;
import com.sam.data.TimeUtils;
import com.sam.data.UserData;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * &lt;br&gt;Created
 *
 * @author wangds
 * @see
 */
public class CouchBaseLiteTest extends InstrumentationTestCase{
    public final static String TAG ="DBTEST_CouchBaseLite";
    private MainActivity mMainActivity;
    private Database db;
    public final static String DB_NAME = "cbl";

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        mMainActivity  = launchActivity("com.sam.nosql", MainActivity.class, null);
        Manager manager = new Manager(new AndroidContext(mMainActivity),Manager.DEFAULT_OPTIONS);
        db = manager.getDatabase(DB_NAME);
//      Manager and Database as Singleton 实际应用官方推荐使用单例模式


    }


    public void testCurd() throws Exception {
        //http://developer.couchbase.com/documentation/mobile/current/develop/training/build-first-android-app/do-crud/index.html

        // Create a new document and add data
        Document document = db.createDocument();
        String documentId = document.getId();
        assertNotNull(documentId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", "Big Party");
        map.put("location", "My House");
        try {
            // Save the properties to the document
            document.putProperties(map);
        } catch (CouchbaseLiteException e) {
            Log.e(TAG, "Error putting", e);
        }
        Log.d(TAG, documentId);

// retrieve the document from the database
        Document retrievedDocument = db.getDocument(documentId);
// display the retrieved document
        Log.d(TAG, "retrievedDocument=" + String.valueOf(retrievedDocument.getProperties()));


        //update
        try {
            // Update the document with more data
            Map<String, Object> updatedProperties = new HashMap<String, Object>();
            updatedProperties.putAll(document.getProperties());
            updatedProperties.put("eventDescription", "Everyone is invited!");
            updatedProperties.put("address", "123 Elm St.");
            // Save to the Couchbase local Couchbase Lite DB
            document.putProperties(updatedProperties);
        } catch (CouchbaseLiteException e) {
            Log.e(TAG, "Error putting", e);
        }


        //Adding an attachment
        try {
        /* Add an attachment with sample data as POC */
            ByteArrayInputStream inputStream = new ByteArrayInputStream(new byte[] { 0, 0, 0, 0 });
            UnsavedRevision revision = document.getCurrentRevision().createRevision();
            revision.setAttachment("binaryData", "application/octet-stream", inputStream);//MIME type
        /* Save doc & attachment to the local DB */
                    revision.save();
        } catch (CouchbaseLiteException e) {
            Log.e(TAG, "Error putting", e);
        }


        Document fetchedSameDoc = db.getExistingDocument(documentId);
        SavedRevision saved = fetchedSameDoc.getCurrentRevision();

// The content of the attachment is a byte[] we created
        Attachment attach = saved.getAttachment("binaryData");
        int i = 0;
        BufferedReader reader = new BufferedReader(new InputStreamReader(attach.getContent()));
        StringBuffer values = new StringBuffer();
        while (i++ < 4) {
            // We knew the size of the byte array
            // This is the content of the attachment
            values.append(reader.read() + " ");
        }
        Log.v(TAG, "The docID: " + documentId + ", attachment contents was: " + values.toString());

//        Delete a document
       boolean deleteResult = retrievedDocument.delete();
        assertTrue(deleteResult);
        Log.d(TAG, "Deleted document, deletion status = " + retrievedDocument.isDeleted());


    }

    public void testList() throws Exception {
        Document document = db.createDocument();
        String docid = document.getId();
        DbDataUtil dbDataUtil = new DbDataUtil();
        TimeUtils.start();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("list", dbDataUtil.list);//50000 无法存储
        document.putProperties(map);
        TimeUtils.end(TAG + " put list ");
        Document  retrievedDocument  =  db.getDocument(docid);
        Map<String, Object> rtMap = retrievedDocument.getProperties();

         List<UserData> readList = (List<UserData>) rtMap.get("list");
        TimeUtils.end(TAG + " read list ");
        assertNotNull(readList);
        assertEquals(dbDataUtil.list.size(),readList.size());
        assertEquals(dbDataUtil.list.get(0).getName(),readList.get(0).getName());
        assertEquals(dbDataUtil.list.get(0),readList.get(0));//map 无法自动序列化成对象
        retrievedDocument.delete();
    }





}
